package mall

/**
这里其实很多重复代码，后面可以写repository封装方法来重构代码
*/
import (
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"mall-go/common"
	"mall-go/dto"
	"mall-go/model"
	"mall-go/response"
	"strconv"
	"time"
)

type IUserAddressController interface {
	IRestController
	AddressList(ctx *gin.Context)
	GetMallUserAddress(ctx *gin.Context)
	GetDefaultMallUserAddress(ctx *gin.Context)
}

type UserAddressController struct {
	DB *gorm.DB
}

// GetDefaultMallUserAddress 获取默认地址
func (u UserAddressController) GetDefaultMallUserAddress(ctx *gin.Context) {
	//获取用户信息
	user, _ := ctx.Get("mallUser")
	userId := user.(model.MallUser).UserID
	defaultAddress := new(model.UserAddress)
	u.DB.Where("user_id = ? and default_flag = 1 and is_deleted = 0", userId).First(&defaultAddress)
	if defaultAddress.AddressID == 0 {
		response.Success(ctx, nil, "无默认地址")
		return
	}
	response.Success(ctx, gin.H{"address": defaultAddress}, "无默认地址")
}

// GetMallUserAddress 获取收货地址详情
func (u UserAddressController) GetMallUserAddress(ctx *gin.Context) {
	addressId, _ := strconv.Atoi(ctx.Params.ByName("addressId"))
	//获取用户信息
	user, _ := ctx.Get("mallUser")
	userId := user.(model.MallUser).UserID
	userAddress := new(model.UserAddress)
	u.DB.Where("address_id = ?", addressId).First(&userAddress)
	addressDTO := dto.ToUserAddressDTO(userAddress)
	if addressDTO.UserID != userId {
		response.Failure(ctx, nil, "非法操作")
		return
	}
	response.Success(ctx, gin.H{"addressDetail": addressDTO}, "查询成功")
}

// AddressList -> 我的收货地址列表/*
func (u UserAddressController) AddressList(ctx *gin.Context) {
	//获取用户信息
	user, _ := ctx.Get("mallUser")
	var addresses []model.UserAddress
	u.DB.Where("user_id = ? and is_deleted = 0", user.(model.MallUser).UserID).Order("address_id desc").Limit(20).Find(&addresses)
	var addressDtos []dto.UserAddressDTO
	//将address中不需要展示给前端的数据处理
	for _, address := range addresses {
		addressDtos = append(addressDtos, dto.ToUserAddressDTO(&address))
	}
	response.Success(ctx, gin.H{"addresses": addressDtos}, "查询成功")
}

// Create 添加地址
func (u UserAddressController) Create(ctx *gin.Context) {
	//获取用户信息
	user, _ := ctx.Get("mallUser")
	userId := user.(model.MallUser).UserID
	var requestAddress model.UserAddress
	ctx.Bind(&requestAddress)
	requestAddress.UserID = userId
	//添加默认地址
	if requestAddress.DefaultFlag == 1 {
		cancelDefaultAddress(ctx, u, userId, requestAddress)
	}
	//设置新的默认地址
	if err := u.DB.Create(&requestAddress).Error; err != nil {
		response.Failure(ctx, nil, "添加失败")
		return
	}
	response.Success(ctx, nil, "添加成功")
}

//取消原默认地址
func cancelDefaultAddress(ctx *gin.Context, u UserAddressController, userId uint, requestAddress model.UserAddress) {
	defaultAddress := new(model.UserAddress)
	u.DB.Where("user_id = ? and default_flag = 1 and is_deleted = 0", userId).First(&defaultAddress)
	//如果有设置默认地址
	if defaultAddress.AddressID != 0 {
		defaultAddress.DefaultFlag = 0
		defaultAddress.UpdateTime = model.Time(time.Now())
		//取消原来的默认地址
		if err := u.DB.Model(&defaultAddress).Update("default_flag", 0).Error; err != nil {
			response.Failure(ctx, nil, "取消原默认地址失败")
			return
		}
	}
}

// Update 修改地址
func (u UserAddressController) Update(ctx *gin.Context) {
	//获取用户信息
	user, _ := ctx.Get("mallUser")
	userId := user.(model.MallUser).UserID
	//前端map新增key会自动转成string类型，导致获取不到地址ID，所以地址ID单独获取
	var requestAddress dto.UserAddressDTO
	ctx.Bind(&requestAddress)
	//根据地址ID查询
	oldAddress := new(model.UserAddress)
	u.DB.Where("address_id = ?", requestAddress.AddressID).First(&oldAddress)
	if oldAddress.AddressID == 0 {
		response.Failure(ctx, nil, "原地址不存在！")
		return
	}
	//检测是否为本用户操作
	if oldAddress.UserID != userId {
		response.Failure(ctx, nil, "非法操作！")
		return
	}

	//设置用户id
	aId, _ := strconv.Atoi(requestAddress.AddressID)
	//封装需要更新的数据
	updateAddress := model.UserAddress{
		AddressID:     uint(aId),
		UserName:      requestAddress.UserName,
		UserPhone:     requestAddress.UserPhone,
		DefaultFlag:   requestAddress.DefaultFlag,
		ProvinceName:  requestAddress.ProvinceName,
		CityName:      requestAddress.CityName,
		RegionName:    requestAddress.RegionName,
		DetailAddress: requestAddress.DetailAddress,
		UpdateTime:    model.Time(time.Now()),
	}
	//修改默认地址
	if requestAddress.DefaultFlag == 1 {
		cancelDefaultAddress(ctx, u, userId, updateAddress)
	}

	//更新地址(这里有坑，gorm默认忽略0值)
	//todo 暂时写两次更新后面再看看怎么修改
	if err := u.DB.Model(&oldAddress).Update(updateAddress).Update("default_flag", updateAddress.DefaultFlag).Error; err != nil {
		response.Failure(ctx, nil, "更新失败")
		return
	}
	response.Success(ctx, nil, "更新成功")
}

// Delete 根据地址id删除
func (u UserAddressController) Delete(ctx *gin.Context) {
	//获取用户信息
	user, _ := ctx.Get("mallUser")
	userId := user.(model.MallUser).UserID
	addressId, _ := strconv.Atoi(ctx.Params.ByName("addressId"))
	//查询地址
	oldAddress := new(model.UserAddress)
	u.DB.Where("address_id = ?", addressId).First(&oldAddress)
	//非本人不能删除
	if oldAddress.UserID != userId {
		response.Failure(ctx, nil, "非法操作")
		return
	}
	if err := u.DB.Where("address_id = ?", addressId).Delete(&oldAddress).Error; err != nil {
		response.Failure(ctx, nil, "删除失败")
		return
	}
	response.Success(ctx, nil, "删除成功")
}

func (u UserAddressController) Query(ctx *gin.Context) {
}

func NewUserAddressController() UserAddressController {
	Db := common.GetDB()
	Db.AutoMigrate(model.UserAddress{})
	return UserAddressController{
		DB: Db,
	}
}
